package com.example.administrator.exkotlin.multimedia.camera

import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import androidx.core.content.FileProvider
import com.example.administrator.exkotlin.R
import kotlinx.android.synthetic.main.activity_camera.*
import java.io.File

/**
 * 摄像头例子
 **/
class CameraActivity : AppCompatActivity() {

    private val takePhotoRequetCode = 1
    private val choosePhotoRequetCode = takePhotoRequetCode + 1
    private lateinit var imageuri: Uri
    private lateinit var outPutImage: File
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera)
        initDatas()
    }

    private fun initDatas() {
        btn_take_picture.setOnClickListener {
            takePicture()
        }
        btn_choose_picture.setOnClickListener {
            choosePicture()
        }


    }

    private fun takePicture() {
        //创建文件
        outPutImage = File(externalCacheDir, "test_image.jpg")
        if (outPutImage.exists()) {
            outPutImage.delete()
        }
        outPutImage.createNewFile()

        //大于安卓7,则需要通过FileProver来获取Uri
        imageuri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            FileProvider.getUriForFile(this, "com.example.camera.fileprovider", outPutImage)
        } else {
            Uri.fromFile(outPutImage)
        }
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri)
        startActivityForResult(intent, takePhotoRequetCode)

    }

    private fun choosePicture() {
        //打开图片选择器
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        //只显示图片
        intent.type = "image/*"
        startActivityForResult(intent, choosePhotoRequetCode)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            takePhotoRequetCode -> {
                if (resultCode == Activity.RESULT_OK) {
                    val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(imageuri))
                    iv_photo.setImageBitmap(bitmap)
                }
            }
            choosePhotoRequetCode -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    data.data?.let { uri ->
                        val bitmap = BitmapFactory.decodeFileDescriptor(contentResolver.openFileDescriptor(uri, "r").fileDescriptor)
                        iv_photo.setImageBitmap(bitmap)
                    }
                }

            }

        }

    }
}
